#include "IPage.h"
#include "AppRouter.h"

void IPage::SetLoadAnim(anim_type_em type, uint16_t time, lv_anim_path_cb_t path) {
	m_anim.attr.type = type;
	m_anim.attr.time = time;
	m_anim.attr.path = path;
}

bool  IPage::PopPageData(void* ptr, uint32_t size) {
	if (m_data.buf == nullptr)
	{
		LV_LOG_WARN("No Stash found");
		return false;
	}

	if (m_data.size != size)
	{
		LV_LOG_WARN(
			"Stash[0x%p](%d) does not match the size(%d)",
			m_data.buf,
			m_data.size,
			size
		);
		return false;
	}

	memcpy(ptr, m_data.buf, m_data.size);
	lv_mem_free(m_data.buf);
	m_data.buf = nullptr;

	return false;
}

bool IPage::GoTo(const char* name, anim_type_em type, const page_data_t* param) {
	AppRouter::GetInstance()->SetSwitchAnim(type);
	return AppRouter::GetInstance()->GoTo(name, param);
}
bool IPage::GoNext(const char* name, anim_type_em type, const page_data_t* param) {
	AppRouter::GetInstance()->SetSwitchAnim(type);
	return AppRouter::GetInstance()->GoNext(name, param); 
}
bool IPage::GoBack(const char* name, anim_type_em type, const page_data_t* param) {
	AppRouter::GetInstance()->SetSwitchAnim(type);
	return AppRouter::GetInstance()->GoBack(name, param); 
}
bool IPage::GoHome() { 
	return AppRouter::GetInstance()->GoHome(); 
}

void IPage::Init(const char* name) {
	m_body = nullptr;
	if (m_name == nullptr)
		m_name = name;
	m_data = { nullptr, 0 };
	m_bReqCache = false;
	m_bCached = false;
	m_timer = nullptr;
	memset(&m_anim, 0, sizeof(m_anim));
}

void IPage::SetTimer(uint32_t time)
{
	if (!m_timer)
		m_timer = lv_timer_create(HandleTimer, time, this);
}
void IPage::HandleTimer(lv_timer_t* timer) {
	IPage* page = (IPage*)timer->user_data;
	LV_ASSERT_NULL(page);
	bool bRet = page->OnTimer();
	if (!bRet) {
		lv_timer_del(page->m_timer);
		page->m_timer = nullptr;
	}
		
}
void IPage::HandleEvent(lv_event_t* event) {
	IPage* page = (IPage*)lv_event_get_user_data(event);
	LV_ASSERT_NULL(page);
	lv_obj_t* obj = lv_event_get_current_target(event);
	lv_event_code_t code = lv_event_get_code(event);

	if (code == LV_EVENT_GESTURE && obj == lv_scr_act()) {
		lv_indev_wait_release(lv_indev_get_act());
		lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());
		if (dir == LV_DIR_LEFT)
			page->OnScrSlideLeft();
		else if (dir == LV_DIR_RIGHT)
			page->OnScrSlideRight();
		else if (dir == LV_DIR_TOP)
			page->OnScrSlideUp();
		else if (dir == LV_DIR_BOTTOM)
			page->OnScrSlideDown();
		else
			LV_LOG_ERROR("Unhandled dir events on screen!");
	}
	else
		page->OnEvent(code, obj);
}